package net.wanho.interceptor;

import net.wanho.constant.LoginConstant;
import net.wanho.entity.UserInfo;
import net.wanho.exception.LoginErrorException;
import net.wanho.util.JwtUtil;
import net.wanho.util.ThreadUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.logging.Logger;

public class LoginInterceptor implements HandlerInterceptor {
    Logger logger = Logger.getLogger(LoginInterceptor.class.getName());
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        String Authorization = request.getHeader("Authorization");
        if (Objects.isNull(Authorization)) {
            // 如果是statics就放行
            if (request.getRequestURI().contains("statics")) {
                return true;
            }
            logger.warning("被拦截的请求路径->" + request.getRequestURI());
            throw new LoginErrorException("请先登录！");
        }

        String token = Authorization.replace(LoginConstant.TOKEN_PREFIX, "");

        if (!JwtUtil.valid(token)) {
            throw new LoginErrorException("登录验证已失效，请重新登录！");
        }

        // 获取用户ID
        Integer userId = JwtUtil.decodeInteger(token, UserInfo.Fields.userId);
        // 将用户ID存入ThreadLocal
        ThreadUtil.setUserId(userId);

        return true;
    }
}
